package sys

import (
	"fmt"
	"sync/atomic"
	"time"
)

type Qps struct {
	lastTotalRequests  uint64
	totalRequests      uint64
	successfulRequests uint64
}

func (qps *Qps) Req() {
	atomic.AddUint64(&qps.totalRequests, 1)
}

func (qps *Qps) Suc() {
	atomic.AddUint64(&qps.successfulRequests, 1)
}

func (qps *Qps) Start() {
	// 启动一个计时器，每秒钟输出统计信息
	go func() {
		for {
			time.Sleep(time.Second)
			total := atomic.LoadUint64(&qps.totalRequests)
			successful := atomic.LoadUint64(&qps.successfulRequests)
			diff := total - qps.lastTotalRequests
			qps.lastTotalRequests = total
			fmt.Printf("QPS: %d, Success Rate: %.2f%%\n", diff, float64(successful)/float64(total)*100)
		}
	}()
}
